<template>
  <div class="health-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>健康数据查看</h2>
        <p class="header-subtitle">实时监控社区老人的健康状况</p>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
      <div class="table-card">
        <div class="card-header">
          <div class="header-icon">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <path d="M10.5 6h3v12h-3V6zm-2 12v-4H5v4H3v-6h5v4zm8 0h-3v-8h3v8zm2-10h-5v2h5v-2z"/>
            </svg>
          </div>
          <h3>健康数据列表</h3>
        </div>

        <!-- 搜索框 -->
        <div class="search-section">
          <div class="search-group">
            <label>老人姓名搜索:</label>
            <input 
              v-model="searchName" 
              @input="currentPage = 1"
              placeholder="请输入老人姓名" 
              class="name-search-input"
            />
          </div>
        </div>

        <div class="card-content">
          <div v-if="loading" class="loading-state">
            <div class="spinner"></div>
            <p>正在加载健康数据...</p>
          </div>
          
          <div v-else-if="filteredHealthData.length === 0" class="empty-state">
            <svg viewBox="0 0 24 24" width="48" height="48" fill="currentColor">
              <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/>
            </svg>
            <p>暂无健康数据</p>
          </div>
          
          <div v-else>
            <div class="table-container">
              <table class="health-table">
                <thead>
                  <tr>
                    <th>老人姓名</th>
                    <th>心率</th>
                    <th>血氧</th>
                    <th>血压</th>
                    <th>睡眠质量</th>
                    <th>位置</th>
                    <th>预警等级</th>
                    <th>记录时间</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="data in currentPageData" :key="data.dataId">
                    <td>
                      <div class="elder-info">
                        <div class="elder-avatar">
                          <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                            <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
                          </svg>
                        </div>
                        {{ data.elderName }}
                      </div>
                    </td>
                    <td>
                      <div class="health-value heart">
                        <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                          <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                        </svg>
                        {{ data.heartRate }}
                      </div>
                    </td>
                    <td>
                      <div class="health-value oxygen">
                        <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                          <path d="M12 2c1.1 0 2 .9 2 2 0 .74-.4 1.38-1 1.73v.77c0 .28.22.5.5.5s.5-.22.5-.5v-.27c.74.35 1.2 1.19 1.2 2.09 0 1.1-.9 2-2 2s-2-.9-2-2c0-.9.46-1.74 1.2-2.09v-.27c0-.28.22-.5.5-.5s.5.22.5.5v.27c-.6-.35-1-.99-1-1.73 0-1.1.9-2 2-2zm0-2C8.14 0 5 3.14 5 7c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                        </svg>
                        {{ data.bloodOxygen }}
                      </div>
                    </td>
                    <td>{{ data.bloodPressure }}</td>
                    <td>{{ data.sleepQuality }}</td>
                    <td>{{ data.location }}</td>
                    <td>
                      <span :class="['alert-tag', getAlertClass(data.alertLevel)]">
                        {{ getAlertText(data.alertLevel) }}
                      </span>
                    </td>
                    <td>{{ data.createTime }}</td>
                    <td>
                      <button class="detail-btn" @click="viewDetail(data)">
                        <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                          <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                        </svg>
                        详情
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 分页组件 -->
            <div class="pagination" v-if="filteredHealthData.length > pageSize">
              <button 
                class="pagination-btn"
                :disabled="currentPage === 1"
                @click="currentPage--"
              >
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12l4.59-4.59z"/>
                </svg>
              </button>
              <span class="page-info">
                第 {{ currentPage }} / {{ totalPages }} 页
              </span>
              <button 
                class="pagination-btn"
                :disabled="currentPage === totalPages"
                @click="currentPage++"
              >
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../../utils/request'

const router = useRouter()
const loading = ref(true)
const currentPage = ref(1)
const pageSize = 10
const searchName = ref('')

const healthDataList = ref([])

// 计算筛选后的健康数据
const filteredHealthData = computed(() => {
  if (!searchName.value) {
    return healthDataList.value
  }
  
  return healthDataList.value.filter(data => 
    data.elderName && data.elderName.includes(searchName.value)
  )
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredHealthData.value.length / pageSize)
})

// 计算当前页数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return filteredHealthData.value.slice(start, end)
})

// 获取健康数据列表
const getHealthData = async () => {
  loading.value = true
  try {
    const res = await request.get('/community/healthData')
    if (res.code === 1) {
      // 为每条记录添加唯一ID（如果不存在dataId）
      healthDataList.value = res.data.map((item, index) => {
        // 如果没有dataId或者dataId为null，则生成一个唯一ID
        if (!item.dataId) {
          // 使用时间戳和索引生成唯一ID
          item.dataId = `generated_${Date.now()}_${index}`
        }
        return item
      })
    }
  } catch (error) {
    console.error('获取健康数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取预警等级样式
const getAlertClass = (level) => {
  switch (level) {
    case 'YELLOW': return 'warning'
    case 'RED': return 'danger'
    default: return 'normal'
  }
}

// 获取预警等级文本
const getAlertText = (level) => {
  switch (level) {
    case 'YELLOW': return '警告'
    case 'RED': return '危险'
    default: return '正常'
  }
}

// 查看详细信息
const viewDetail = (data) => {
  // 检查dataId是否存在且有效
  if (!data || !data.dataId) {
    console.error('Missing or invalid dataId in health data:', data);
    alert('该健康数据记录缺少必要信息，无法查看详情。');
    return;
  }
  
  // 将数据存储到 sessionStorage
  sessionStorage.setItem('healthDataDetail', JSON.stringify(data));
  router.push({
    name: 'HealthDetail',
    params: { dataId: data.dataId }
  })
}
onMounted(() => {
  getHealthData()
})
</script>

<style scoped>
.health-page {
  padding: 24px;
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f2ff 100%);
  min-height: 100%;
}

.page-header {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.header-subtitle {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.main-content {
  max-width: 1800px;
  margin: 0 auto;
}

.table-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  overflow: hidden;
}

.card-header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 20px 24px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  width: 24px;
  height: 24px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.search-section {
  height: 60px;
  padding: 16px 24px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.search-group {
  height: 100%;
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-group label {
  font-weight: 500;
  color: #495057;
}

.search-group .name-search-input {
  padding: 6px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  background-color: white;
  min-width: 200px;
}

.card-content {
  padding: 24px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #6c757d;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e9ecef;
  border-top: 4px solid #4facfe;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-state p {
  margin: 0;
  font-size: 16px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #6c757d;
}

.empty-state svg {
  color: #ced4da;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0;
  font-size: 16px;
}

.table-container {
  overflow-x: auto;
}

.health-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 800px;
}

.health-table th,
.health-table td {
  padding: 16px 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.health-table th {
  background: #fafafa;
  font-weight: 600;
  color: #495057;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.elder-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.elder-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4facfe;
}

.health-value {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.health-value.heart {
  color: #ff6b6b;
}

.health-value.oxygen {
  color: #4facfe;
}

.alert-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.alert-tag.normal {
  background: #e8f7ef;
  color: #28a745;
}

.alert-tag.warning {
  background: #fff3cd;
  color: #856404;
}

.alert-tag.danger {
  background: #f8d7da;
  color: #721c24;
}

.detail-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(79, 172, 254, 0.2);
}

.detail-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(79, 172, 254, 0.3);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 24px 0 0;
  gap: 16px;
}

.pagination-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border: 1px solid #dee2e6;
  background: #fff;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #495057;
}

.pagination-btn:hover:not(:disabled) {
  background: #4facfe;
  border-color: #4facfe;
  color: #fff;
}

.pagination-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-info {
  color: #495057;
  font-size: 14px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .health-page {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .health-table th,
  .health-table td {
    padding: 12px 8px;
    font-size: 13px;
  }
  
  .detail-btn {
    padding: 4px 8px;
    font-size: 11px;
  }
  
  .search-group {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-group .name-search-input {
    min-width: auto;
    width: 100%;
  }
}
</style>